<template>
    <el-dialog
        v-model="visible"
        :title="form.tenant_id ? '编辑租户' : '新增租户'"
        width="500px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            status-icon
        >
            <el-form-item label="学校名称" prop="tenant_name">
                <el-input v-model="form.tenant_name" placeholder="请输入学校名称"/>
            </el-form-item>
            <el-form-item label="学院名称" prop="collegeName" required>
                <template v-if="!form.tenant_id">
                    <el-input
                        v-model="form.collegeName"
                        placeholder="请输入学院名称"
                    />
                </template>
                
                <div v-else class="managed-colleges">
                    <div class="college-item" v-for="(item, index) in form.collegeList" :key="index">
                        <span class="college-count">{{ index + 1 }}</span>
                        <el-input 
                            v-model="item.name"
                            class="college-name-input"
                            :placeholder="item.name ? '' : '请输入学院名称'"
                        />
                    </div>
                </div>
            </el-form-item>

            <el-form-item label="用户名" prop="user_name">
                <el-input v-model="form.user_name" placeholder="请输入管理员用户名"/>
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input 
                    v-model="form.password" 
                    type="password" 
                    placeholder="请输入管理员密码"
                    show-password
                />
            </el-form-item>
            <el-form-item label="学校logo" prop="logo_url">
                <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="uploadImage"
                >
                    <img v-if="form.logo_url" :src="form.logo_url" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="负责人" prop="contact_person">
                <el-input v-model="form.contact_person" placeholder="请输入负责人姓名"/>
            </el-form-item>

            <el-form-item label="联系电话" prop="contact_phone">
                <el-input v-model="form.contact_phone" placeholder="请输入联系电话"/>
            </el-form-item>

            <el-form-item label="过期时间" prop="expire_date">
                <el-date-picker
                    v-model="form.expire_date"
                    type="date"
                    placeholder="选择过期时间"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>

            <el-form-item label="租户状态" prop="is_active">
                <el-switch v-model="form.is_active" />
            </el-form-item>

            <el-form-item label="备注" prop="remarks">
                <el-input
                    v-model="form.remarks"
                    type="textarea"
                    placeholder="请输入备注信息"
                />
            </el-form-item>


        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="loading">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { tenantAdd, tenantUpdate } from '@/api/admin/tenant'
import {UploadPicMin} from '@/utils/minioUpload';
const emit = defineEmits(['success'])
const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)

const form = reactive({
    tenant_id: '',
    tenant_name: '',
    collegeName: '',
    user_name: '',
    password: '',
    logo_url: '',
    contact_person: '',
    contact_phone: '',
    expire_date: '',
    is_active: true,
    remarks: '',
    collegeList: []
})

const rules = {
    tenant_name: [
        { required: true, message: '请输入学校名称', trigger: 'blur' }
    ],
    contact_person: [
        { required: true, message: '请输入负责人姓名', trigger: 'blur' }
    ],
    contact_phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    expire_date: [
        { required: true, message: '请选择过期时间', trigger: 'change' }
    ],
    collegeName: [
        { 
            required: true, 
            validator: (rule, value, callback) => {
                if (!form.tenant_id) {
                    // 新增场景
                    if (!value) {
                        callback(new Error('请输入学院名称'))
                    } else {
                        callback()
                    }
                } else {
                    // 修改场景
                    if (form.collegeList && form.collegeList.length > 0) {
                        const hasEmptyName = form.collegeList.some(college => !college.name)
                        if (hasEmptyName) {
                            callback(new Error('请输入学院名称'))
                        } else {
                            callback()
                        }
                    } else {
                        callback(new Error('请输入学院名称'))
                    }
                }
            },
            trigger: 'blur'
        }
    ],
    user_name: [
        { required: true, message: '请输入管理员用户名', trigger: 'blur' }
    ],
    password: [
        { 
            // required: true, message: '请输入管理员密码', trigger: 'blur',
            validator: (rule, value, callback) => {
                // 如果是编辑模式且密码未修改（还是默认值），则跳过验证
                if (form.tenant_id && value === '••••••') {
                    callback()
                    return
                }
                
                // 如果是新增模式或密码已被修改，则进行验证
                if (!value) {
                    callback(new Error('请输入密码'))
                    return
                }
                if (value.length < 6) {
                    callback(new Error('密码长度不能少于6个字符'))
                    return
                }
                
                if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/.test(value)) {
                    callback(new Error('密码必须包含字母和数字'))
                    return
                }
                
                callback()
            },
            trigger: 'blur'
        }
    ],
}

const resetForm = () => {
    Object.assign(form, {
        tenant_id: '',
        tenant_name: '',
        collegeName: '',
        user_name: '',
        password: '',
        logo_url: '',
        logo_url_id:'',
        contact_person: '',
        contact_phone: '',
        expire_date: '',
        is_active: true,
        remarks: '',
        collegeList: []
    })
}

const open = (row = null) => {
    visible.value = true
    resetForm()
    if (row) {
        const colleges = row.arch_info || []
        Object.assign(form, {
            ...row,
            password: '••••••',
            collegeList: colleges.map(college => ({
                id: college.id,
                name: college.name,
                count: college.count
            }))
        })
    }
}

const handleClose = () => {
    visible.value = false
    resetForm()
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const beforeAvatarUpload = (file) => {

    
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

const uploadImage = async (params) => {

    const file=params.file
    // 从file文件中读取blob
    if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const arrayBuffer = e.target.result;
            // 创建一个新的 Blob
            const newBlob = new Blob([arrayBuffer], { type: file.type });


            console.log(file,newBlob);
            
            // 你可以在这里进一步处理 newBlob，上传到服务器等
            // 将图像上传到服务器
              UploadPicMin(file, newBlob).then(file_id=>{
                form.logo_url_id=file_id
              })
            // 生成临时的url图像
              const url = URL.createObjectURL(file);
              form.logo_url=url      
        };
          reader.readAsArrayBuffer(file);
        
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                // 构建提交数据
                const submitData = {
                    ...form,
                    arch_info: form.tenant_id ? form.collegeList.map(college => ({
                        id: college.id,
                        name: college.name
                    })) : undefined
                }
                
                // 如果是新增，则删除空的 tenant_id，并添加 college_name
                if (!submitData.tenant_id) {
                    delete submitData.tenant_id
                    submitData.college_name = submitData.collegeName
                }
                
                // 如果密码是黑点或为空，则不提交密码字段
                if (!submitData.password || submitData.password === '••••••') {
                    delete submitData.password
                }
                const api = form.tenant_id ? tenantUpdate : tenantAdd
                submitData.tenant_id = submitData.tenant_id ? submitData.tenant_id.toString() : '';
                // 未对接图片上传，所以logo_url_id先瞎设置一个
                // submitData.logo_url_id = '123';
                submitData.logo_url_id = submitData.logo_url_id ? submitData.logo_url_id.toString() : '';

                console.log(submitData);
                
                const res = await api(submitData)
                // 新增接口返回200状态码表示成功，编辑接口返回res
                if ((form.tenant_id && res) || (!form.tenant_id && res === '')) {
                    ElMessage.success(form.tenant_id ? '修改成功' : '添加成功')
                    emit('success')
                    handleClose()
                } else {
                    ElMessage.error(form.tenant_id ? '修改失败' : '添加失败')
                }
            } catch (error) {
                console.error('提交失败:', error)
                ElMessage.error(form.tenant_id ? '修改失败' : '添加失败')
            } finally {
                loading.value = false
            }
        }
    })
}

const getEditData = async () => {
    // 原有代码...
    form.collegeList = [
        { count: 9, name: 'V学院名称' },
        { count: 5, name: '计算机学院' }
    ]
    // 原有代码...
}

defineExpose({
    open
})
</script>

<style scoped>
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.college-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 8px 12px;
    background: #f5f7fa;
    border-radius: 4px;
    
    .college-count {
        min-width: 24px;
        font-size: 16px;
        font-weight: bold;
        color: #409EFF;
        margin-right: 12px;
    }
    
    .college-name-input {
        flex: 1;
        
        :deep(.el-input__wrapper) {
            background: transparent;
            box-shadow: none;
            
            &:hover, &.is-focus {
                box-shadow: 0 0 0 1px #409EFF;
            }
        }
    }
}

.delete-btn {
    margin-left: 8px;
    color: #F56C6C;
}

.delete-btn:hover {
    color: #f89898;
}

.managed-colleges {
    .college-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        padding: 8px 12px;
        background: #f5f7fa;
        border-radius: 4px;
        
        .college-count {
            min-width: 24px;
            font-size: 16px;
            font-weight: bold;
            color: #409EFF;
            margin-right: 12px;
        }
        
        .college-name-input {
            flex: 1;
            
            :deep(.el-input__wrapper) {
                background: transparent;
                box-shadow: none;
                
                &:hover, &.is-focus {
                    box-shadow: 0 0 0 1px #409EFF;
                }
            }
        }
    }
}
</style>
